package com.star.spring.sharding.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.star.spring.sharding.entity.Order;
import com.star.spring.sharding.entity.OrderItem;
import com.star.spring.sharding.service.OrderItemService;
import com.star.spring.sharding.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/test")
public class ShardingTestController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    /**
     * 测试分片插入
     */
    @PostMapping("/sharding")
    public String testSharding() {
        // 插入多个订单来测试分片
        for (int i = 0; i < 10; i++) {
            // 使用不同的user_id来测试数据库分片
            Long userId = (long) (i + 1);
            Long addressId = (long) (i + 1);
            
            // 创建订单
            Order order = new Order(userId, addressId, "TEST");
            orderService.save(order);
            
            // 创建订单项
            OrderItem orderItem = new OrderItem(order.getOrderId(), userId, 
                "测试商品" + i, new BigDecimal("99.99"), i + 1);
            orderItemService.save(orderItem);
        }
        
        return "分片测试数据插入成功";
    }

    /**
     * 测试分片查询
     */
    @GetMapping("/sharding/query")
    public String testShardingQuery() {
        StringBuilder result = new StringBuilder();
        
        // 查询所有订单
        List<Order> orders = orderService.list();
        result.append("订单总数: ").append(orders.size()).append("\n");
        
        // 根据user_id查询订单（测试数据库分片）
        for (long userId = 1; userId <= 5; userId++) {
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            List<Order> userOrders = orderService.list(wrapper);
            result.append("用户").append(userId).append("的订单数: ").append(userOrders.size()).append("\n");
        }
        
        // 根据order_id查询订单（测试表分片）
        if (!orders.isEmpty()) {
            Long orderId = orders.get(0).getOrderId();
            Order order = orderService.getById(orderId);
            result.append("根据订单ID查询: ").append(order != null).append("\n");
        }
        
        return result.toString();
    }
}